package flex.cc.store.util;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.util.encoders.UrlBase64;

/**
 * 
 * @author WANGCONG 2021年12月20日下午14:25:36
 * @desc 下游网点推送、代驾预约服务：加密、解密、验签工具类
 */
public class PushDecryptUtil {

	// key3Des：测试、生产参数值一样
	//private static String key3Des = "C205BC5839533270jUN1d77Y";
	
	private static final String CRYPT_ALGORITHM = "DESede";

	public static void main(String[] args) {
		System.out.println("接口返回参数" + "aaaaa");
		// 拿到返回参数中encryptJsonStr 调用jiemi(encryptJsonStr) 验签 拿取明文;
	}

	// 解密
	public static String jiemi(String jsonStr,String storeSourceKey,String key3Des) {
		
		// 此参数为接口返回body中encryptJsonStr
		try {
			jsonStr = decrypt(jsonStr, key3Des);
			String decryptStr = jsonStr.split("[|]")[0]; //数据报文
			String sign = jsonStr.split("[|]")[1];       //验签sign
			verifyTheEncryKey(decryptStr, storeSourceKey, sign);
			System.out.println(decryptStr);
			return decryptStr;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	

	// 解密
	public static String decrypt(String value, String key){
		try {
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), CRYPT_ALGORITHM);
			Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			byte[] decodedByte = UrlBase64.decode(value.getBytes("UTF-8"));
			byte[] decryptedByte = cipher.doFinal(decodedByte);
			return new String(decryptedByte, "UTF-8");
		} catch (Exception e) {
			System.out.println("PushDecryptUtil.decrypt : decrypt was failed!");
			return "";
		}
	}

	// 验签
	public static void verifyTheEncryKey(String decryptStr, String encryKey, String sign) {
		StringBuffer stn = new StringBuffer();
		stn.append(decryptStr).append(encryKey);
		String paramSign = null;
		try {
			paramSign = DigestUtils.md5Hex(stn.toString().getBytes("UTF-8")).toUpperCase();
		} catch (UnsupportedEncodingException e1) {
		}
		if (!sign.equals(paramSign)) {
			// 验签失败

		} else {
			// 验签成功
		}
	}
	
	//加密
	public static String encrypt(String jsonStr,String key3Des) throws Exception{
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key3Des.getBytes("UTF-8"), CRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            
            byte[] encryptedByte = cipher.doFinal(jsonStr.getBytes("UTF-8"));
            byte[] encodedByte = UrlBase64.encode(encryptedByte);
            return new String(encodedByte,"UTF-8");
        } catch(Exception e) {
        	System.out.println("PushDecryptUtil.encrypt : encrypt was failed!");
			return "";
        }
    }
	

}
